<?php

namespace App\Http\Controllers\family;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Logic\FundLogic;

class FundController extends Controller
{
    protected $fundLogic;

    public function __construct()
    {
        $this->fundLogic = new FundLogic();
        // 添加认证中间件，确保用户已登录
        $this->middleware('auth:sanctum');
    }

    // 创建家庭基金
    public function createFund(Request $request)
    {
        // 验证输入的基金会名称
        $request->validate([
            'fund_name' => 'required|string|max:255',
        ]);

        $params = $request->all();
        dd(auth()->user()->id);
        // 获取当前登录用户ID
        $userId = auth()->user()->id;
        // 调用逻辑层处理业务
        $result = $this->fundLogic->createFund($params, $userId);

        return $this->success($result);
    }

    // 基金详情
    public function fundDetails(Request $request)
    {
        // 验证基金ID
        $request->validate([
            'fund_id' => 'required|integer|exists:family_funds,id',
        ]);
        $params = $request->all();
        $fundId = $params['fund_id'];

        // 调用逻辑层获取基金详情
        $result = $this->fundLogic->getFundDetails($fundId);

        // 检查是否有错误
        if (isset($result['error'])) {
            return $this->error($result['error']);
        }

        return $this->success($result);
    }

    //更新基金简介
    public function updateFundDescription(Request $request)
    {
        // 验证基金ID
        $request->validate([
            'fund_id' => 'required|integer|exists:family_funds,id',
            'description' => 'required|string|max:255',
        ]);
        $params = $request->all();
        // 调用逻辑层获取基金详情
        $result = $this->fundLogic->updateFundDescription($params['fund_id'], $params['description']);
        if (isset($result['error'])) {
            return $this->error($result['error']);
        }
        return $this->success($result);
    }

    public function order(Request $request)
    {
        $params = $request->all();

    }

    // 开通基金
    public function openFund(Request $request)
    {
        // 验证输入参数
        $request->validate([
            'fund_name' => 'required|string|max:255',
            'amount' => 'required|integer|min:10000',
        ]);

        $params = $request->all();

        // 获取当前登录用户ID
        $userId = auth()->user()->id;
        // 调用逻辑层处理业务
        $result = $this->fundLogic->openFund($params, $userId);

        // 检查是否有错误
        if (isset($result['error'])) {
            return $this->error($result['error']);
        }

        return $this->success($result);
    }
}
